package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.reggie.bean.User;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.common.ValidateCodeUtils;
import com.zrrd.reggie.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userServie;
    @Autowired
    private RedisTemplate redisTemplate;
    //获取验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取传递过来的手机号
        String phone = user.getPhone();
        //非空判断
        if (StringUtils.isNotEmpty(phone)) {
            //生成一个随机验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            System.out.println("生成的验证码====>" + code);
            //调用阿里云发送信息
            //SMSUtils.sendMessage("ABC商城","SMS_463600053",phone,code+"");
            //将生成的验证码存入到session中
            //request.getSession().setAttribute("code", code + "");
            //将验证码存入到Redis中
            redisTemplate.opsForValue().set(phone,code+"",5, TimeUnit.MINUTES);
            return R.success("短信验证码发送成功");
        }
        return R.error("短信验证码发送失败");
    }

    //登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest request) {
        //获取参数
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session中获取之前存入的验证码
        //String sessionCod = (String) request.getSession().getAttribute("code");
        //从Redis中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        //检验验证码
        if (redisCode != null && redisCode.equals(code)) {
            //根据手机号查询User表
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            User user = userServie.getOne(wrapper);
            //如果用户不存在
            if (user == null) {
                //创建一个新用户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                //执行保存
                userServie.save(user);
            }
            //将用户信息存到session中
            request.getSession().setAttribute("userId", user.getId());
            //删除Redis中的验证码
            redisTemplate.delete(phone);
            //返回用户信息
            return R.success(user);
        }
        return R.error("验证码错误");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request) {
        request.getSession().removeAttribute("userId");
        return R.success("退出登录成功");
    }

}
